<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>对象类型</title>
    <script>
        function f1() {
            // 使用js内置对象类型Object
            let obj = new Object();
            // 该类型可以使用任意属性
            // 当为指定属性赋值之后,相当于声明了该属性
            obj.id = 1;
            obj.name = "admin";
            obj.age = 20;
            obj.hobbies = ["吃饭", "睡觉", "打豆豆"]
            obj.show = () => {
                console.log("编号:" + obj.id + ",姓名:" + obj.name + ",age:" + obj.age + ",hobbies:" + obj.hobbies)
            }

            // 只展示有值的属性
            console.log(obj);
            console.log(obj.name);
            console.log(obj.age);
            obj.show();
        }

        function f2() {
            let user = new User(1, "admin", "123456");
            console.log(user);
        }

        function User(id, username, password) {
            this.id = id;
            this.username = username;
            this.password = password;
        }

        function f3() {
            let user = {"id": 1, "username": "alex", "password": "666666"}
            console.log(typeof user)
            console.log(user)
        }

        function f4() {
            let user = "{'id':1,'username':'alex','password':'666666'}";
            console.log(typeof user);

            // 有两种方式进行转换
            // 1.使用eval函数,该方法属于通用方法,但是安全性较低
            let obj = eval("(" + user + ")");
            console.log(obj)
            console.log(typeof obj)

            // 2.使用JSON.parse()进行转换,该方式安全性较高
            // 但是该方式存在限制:限制JSON格式的字符串只能使用单引号
            let user2 = '{"id":1,"username":"alex","password":"666666"}';
            // let obj2 = JSON.parse(user); // 报错
            let obj2 = JSON.parse(user2);
            console.log(obj2)
            console.log(typeof obj2)
        }

    </script>
</head>
<body>
<button onclick="f1()">定义方式一</button>
<br>
<button onclick="f2()">定义方式二</button>
<br>
<button onclick="f3()">JSON对象</button>
<br>
<button onclick="f4()">将JSON格式字符串转换成JSON对象</button>
</body>
</html>